package com.alu4r.atcrowdfunding.potal.controller;


import com.alu4r.atcrowdfunding.VO.Data;
import com.alu4r.atcrowdfunding.bean.Cert;
import com.alu4r.atcrowdfunding.bean.Member;
import com.alu4r.atcrowdfunding.bean.MemberCert;
import com.alu4r.atcrowdfunding.bean.Ticket;

import com.alu4r.atcrowdfunding.manager.service.CertService;
import com.alu4r.atcrowdfunding.potal.listener.PassListener;
import com.alu4r.atcrowdfunding.potal.listener.RefuseListener;
import com.alu4r.atcrowdfunding.potal.service.MemberService;
import com.alu4r.atcrowdfunding.potal.service.TicketService;
import com.alu4r.atcrowdfunding.util.Constant;
import com.alu4r.atcrowdfunding.util.JsonMessageResult;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;


@Controller
@RequestMapping("/member")
public class MemberController {


    @Autowired
    private MemberService memberService;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private CertService certService;

    @Autowired
    private RepositoryService repositoryService ;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;


    @RequestMapping("/checkAuthCode")
    public String finish() {
        System.out.println("去输入验证码页面");
        return "member/checkAuthCode";
    }
    @RequestMapping("/checkEmail")
    public String checkEmail() {
        System.out.println("去验证邮箱页面");
        return "member/checkEmail";
    }


    @ResponseBody
    @RequestMapping("/finishApply")
    public JsonMessageResult finishApply( HttpSession session, String authcode) {
        JsonMessageResult jsonMessageResult;

        try {

            // 获取登录会员信息
            Member loginMember = (Member)session.getAttribute(Constant.LOGIN_MEMBER);


            //让当前系统用户完成:验证码审核任务.
            Ticket ticket = ticketService.getTicketByMemberId(loginMember.getId()) ;
            if(ticket.getAuthcode().equals(authcode)){
                //完成审核验证码任务
                //TaskQuery taskQuery = taskService.createTaskQuery();

                Task task = taskService.createTaskQuery().processInstanceId(ticket.getPiid()).taskAssignee(loginMember.getLoginacct()).singleResult();

                taskService.complete(task.getId());

                //更新用户申请状态
                loginMember.setAuthstatus("1");
                memberService.updateAuthstatus(loginMember);


                //记录流程步骤:
                ticket.setPstep("finishapply");
                ticketService.updatePstep(ticket);
                jsonMessageResult = JsonMessageResult.success();
            }else{
                jsonMessageResult = JsonMessageResult.fail();
                jsonMessageResult.setMessage("用户验证码输入错误");
            }
        } catch( Exception e ) {
            e.printStackTrace();
            jsonMessageResult = JsonMessageResult.fail();
            jsonMessageResult.setMessage("未知错误");
        }

        return jsonMessageResult;

    }

    @ResponseBody
    @RequestMapping("/startProcess")
    public JsonMessageResult startProcess(HttpSession session, String email) {
        JsonMessageResult jsonMessageResult;
        try {
            Member loginMember = (Member) session.getAttribute(Constant.LOGIN_MEMBER);
            // 查看是否有更邮箱
            if(!loginMember.getEmail().equals(email)){
                loginMember.setEmail(email);
                memberService.updateEmail(loginMember);
            }
            //验证码生成
            StringBuffer authcode = new StringBuffer();
            for (int i = 0; i < 4; i++) {
                authcode.append(new Random().nextInt(10));
            }

            //启动流程
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("auth").singleResult();
            Map<String, Object> variables = new HashMap();
            variables.put("toEmail",email);
            variables.put("authcode",authcode);
            variables.put("loginacct",loginMember.getLoginacct());
            variables.put("passListener",new PassListener());
            variables.put("refuseListener",new RefuseListener());

            ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), variables);
            //记录流程步骤
            Ticket ticketByMemberId = ticketService.getTicketByMemberId(loginMember.getId());
            ticketByMemberId.setPstep("checkemail");
            ticketByMemberId.setPiid(processInstance.getId());
            ticketByMemberId.setAuthcode(authcode.toString());
            ticketService.updateTicket(ticketByMemberId);

            jsonMessageResult = JsonMessageResult.success();
        } catch (Exception e) {
            jsonMessageResult = JsonMessageResult.fail();
            e.printStackTrace();
        }
        return jsonMessageResult;
    }
    //上传实名认证的证明
    @ResponseBody
    @RequestMapping("/doUploadCert")
    public JsonMessageResult doUploadCert(HttpSession session, Data ds) {
        JsonMessageResult jsonMessageResult;
        System.out.println("资质证明上传中*************************");
        System.out.println("资质证明上传中*************************");
        System.out.println("资质证明上传中*************************");
        System.out.println("资质证明上传中*************************");
        try {
            Member loginMember = (Member) session.getAttribute(Constant.LOGIN_MEMBER);
            List<MemberCert> certImgs = ds.getCertimgs();

            String realPath = session.getServletContext().getRealPath("/pics");

            for (MemberCert certImg : certImgs) {
                MultipartFile fileImg = certImg.getFileImg();
                String extName = fileImg.getOriginalFilename().substring(fileImg.getOriginalFilename().lastIndexOf("."));
                String tmpName = UUID.randomUUID() + extName;

                String fileName = realPath + "/cert" + "/" +tmpName;
                fileImg.transferTo(new File(fileName));
                certImg.setIconpath(tmpName);
                certImg.setMemberid(loginMember.getId());
            }
            certService.saveMemberCert(certImgs);
            //记录流程步骤
            Ticket ticketByMemberId = ticketService.getTicketByMemberId(loginMember.getId());
            ticketByMemberId.setPstep("uploadCert");
            ticketService.updatePstep(ticketByMemberId);


            jsonMessageResult = JsonMessageResult.success();
        } catch (Exception e) {
            jsonMessageResult = JsonMessageResult.fail();
            e.printStackTrace();
        }
        return jsonMessageResult;
    }


    //判断前面的流程是不是都已经走过了
    @RequestMapping("/apply")
    public String apply(HttpSession session){
        Member member = (Member) session.getAttribute(Constant.LOGIN_MEMBER);
        Ticket ticket = ticketService.getTicketByMemberId(member.getId());
        if(ticket == null){
            ticket = new Ticket();
            ticket.setMemberid(member.getId());
            ticket.setPstep("apply");
            ticket.setStatus("0");
            ticketService.saveTicket(ticket);
        }else {
            System.out.println("记录到您已经选择了账户类型");
            String pstep = ticket.getPstep();
            if("accttype".equals(pstep)){
                return "redirect:/member/basicInfo.htm";
            }else if("basicInfo".equals(pstep)){
                System.out.println("记录到您已经完成了第一步，现在完成第二步");
                //查询第二步需要上传哪些资质证明
                List<Cert> certs = certService.queryCertByAccttype(member.getAccttype());
                session.setAttribute("certs",certs);
                return "redirect:/member/toUploadCert.htm";
            }else if("uploadCert".equals(pstep)){

                return "redirect:/member/checkEmail.htm";
            }else if("checkemail".equals(pstep)){

                return "redirect:/member/checkAuthCode.htm";
            }else if("finishapply".equals(pstep)){
                System.out.println("认证完成");
               return "member/index";
            }
        }
        return "member/acctType";
    }

    @RequestMapping("/toUploadCert")
    public String uploadCert(HttpSession session) {
        Member member = (Member) session.getAttribute(Constant.LOGIN_MEMBER);
        List<Cert> certs = certService.queryCertByAccttype(member.getAccttype());
        session.setAttribute("certs",certs);
        System.out.println("进入第二个步骤页面");
        return "member/uploadCert";
    }


    //更新第一步骤信息
    @ResponseBody
    @RequestMapping("/updateBasicInfo")
    public JsonMessageResult updateBasicInfo(HttpSession session, Member member) {

        JsonMessageResult jsonMessageResult;
        Member loginMember = (Member) session.getAttribute(Constant.LOGIN_MEMBER);
        loginMember.setRealname(member.getRealname());
        loginMember.setCardnum(member.getCardnum());
        loginMember.setTel(member.getTel());
        System.out.println(loginMember.toString());
        try {
            memberService.updateBasicInfo(loginMember);
            //记录流程步骤
            Ticket ticketByMemberId = ticketService.getTicketByMemberId(loginMember.getId());
            ticketByMemberId.setPstep("basicInfo");
            ticketService.updatePstep(ticketByMemberId);
            jsonMessageResult = JsonMessageResult.success();
        } catch (Exception e) {
            jsonMessageResult = JsonMessageResult.fail();
            e.printStackTrace();
        }
        return jsonMessageResult;
    }


    //跳转到申请流程页面
    @RequestMapping("/basicInfo")
    public String basicInfo() {
        System.out.println("进入第一个步骤页面");
        return "member/basicInfo";
    }


    /**
     * 更新账户类型
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateAcctType")
    public JsonMessageResult updateAcctType(HttpSession session, String accttype) {
        System.out.println("发起账户类型更新");
        JsonMessageResult jsonMessageResult;
        Member member = (Member) session.getAttribute(Constant.LOGIN_MEMBER);
        member.setAccttype(accttype);
        try {
            memberService.updateAcctType(member);
            //记录流程步骤
            Ticket ticketByMemberId = ticketService.getTicketByMemberId(member.getId());
            ticketByMemberId.setPstep("accttype");
            ticketService.updatePstep(ticketByMemberId);


            jsonMessageResult = JsonMessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            jsonMessageResult = JsonMessageResult.fail();
        }
        return jsonMessageResult;
    }

    @RequestMapping("/toAcctType")
    public String toAcctType() {
        System.out.println("进入实名认证页面");
        return "member/acctType";
    }

    @RequestMapping("/toIndex")
    public String toIndex() {
        System.out.println("进入member页面");
        return "member/index";
    }
}
